from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

# 加载图像（灰度图）
img = Image.open("images/example.jpg").convert("L")  # 转为灰度
A = np.array(img)

# SVD 分解
U, Sigma, VT = np.linalg.svd(A)

# 只取前 10 个奇异值重建图像
k = 10
Sigma_k = np.diag(Sigma[:k])
U_k = U[:, :k]
VT_k = VT[:k, :]
A_compressed = U_k @ Sigma_k @ VT_k

# 显示原图和压缩图
plt.subplot(1, 2, 1)
plt.imshow(A, cmap="gray")
plt.title("Original Image")

plt.subplot(1, 2, 2)
plt.imshow(A_compressed, cmap="gray")
plt.title(f"Compressed (k={k})")
plt.show()